<template>
  <div>
    <cube-form
      :model="model"
      :schema="schema"
      :immediate-validate="false"
      :options="options"
      @validate="validateHandler"
      @submit="submitHandler"
      @reset="resetHandler"
    ></cube-form>
  </div>
</template>

<script>
import { apiShopAdmin } from '@/properties/api.js'
import axios from 'axios'
import VerifyCode from './common/VerifyCode'
export default {
  data () {
    return {
      validity: {},
      valid: undefined,
      model: {
        shopName: '我的店铺',
        shopCategory: '',
        shopArea: '',
        shopAddr: '详细地址',
        shopPhone: '15029057276',
        shopImg: [],
        shopDesc: '商铺简介',
        verifyCode: ''
      },
      schema: {
        groups: [
          {
            legend: '商铺信息',
            fields: [
              {
                type: 'input',
                modelKey: 'shopName',
                label: '商铺名称',
                props: {
                  placeholder: '请输入商铺名称'
                },
                rules: {
                  required: true
                },
                trigger: 'blur'
              },
              {
                type: 'select',
                modelKey: 'shopCategory',
                label: '商铺分类',
                props: {
                  placeholder: '请选择商铺分类',
                  options: []
                },
                rules: {
                  required: true
                }
              },
              {
                type: 'select',
                modelKey: 'shopArea',
                label: '所属地区',
                props: {
                  placeholder: '请选择所属地区',
                  options: []
                },
                rules: {
                  required: true
                }
              },
              {
                type: 'input',
                modelKey: 'shopAddr',
                label: '详细地址',
                props: {
                  placeholder: '请输入详细地址'
                },
                rules: {
                  required: true
                },
                trigger: 'blur'
              },
              {
                type: 'input',
                modelKey: 'shopPhone',
                label: '联系电话',
                props: {
                  placeholder: '请输入联系电话'
                },
                rules: {
                  required: true
                },
                trigger: 'blur'
              },
              {
                type: 'upload',
                modelKey: 'shopImg',
                label: '缩略图',
                props: {
                  max: 1
                },
                events: {
                  'file-removed': (...args) => {
                    console.log('file removed', args)
                  }
                },
                rules: {
                  required: true,
                  uploaded: (val, config) => {
                    return Promise.all(
                      val.map((file, i) => {
                        return new Promise((resolve, reject) => {
                          if (file.uploadedUrl) {
                            return resolve()
                          }
                          setTimeout(() => {
                            if (i % 2) {
                              reject(new Error())
                            } else {
                              file.uploadedUrl = 'uploaded/url'
                              resolve()
                            }
                          }, 1000)
                        })
                      })
                    ).then(() => {
                      return true
                    })
                  }
                },
                messages: {
                  uploaded: '上传失败'
                }
              },
              {
                type: 'textarea',
                modelKey: 'shopDesc',
                label: '商铺简介',
                props: {
                  placeholder: '请输入商铺简介',
                  maxlength: 300
                },
                rules: {
                  required: true
                },
                debounce: 100
              },
              {
                type: 'input',
                modelKey: 'verifyCode',
                label: '验证码',
                props: {
                  placeholder: '请输入验证码'
                },
                rules: {
                  required: true
                },
                debounce: 100
              },
              {
                component: VerifyCode,
                label: ' ',
                props: {
                  sign: 1
                }
              }
            ]
          },
          {
            fields: [
              {
                type: 'submit',
                label: '提交',
                props: {
                  primary: true
                }
              },
              {
                type: 'reset',
                label: '重置'
              },
              {
                type: 'button',
                label: '返回',
                events: {
                  click: () => {
                    console.log('sss')
                  }
                }
              }
            ]
          }
        ]
      },
      options: {
        scrollToInvalidField: true,
        layout: 'standard'
      }
    }
  },
  mounted () {
    this.handleAreas()
    this.handleShopCategories()
  },
  methods: {
    submitHandler (e) {
      e.preventDefault()
      this.handleSubmit()
    },

    validateHandler (result) {
      this.validity = result.validity
      this.valid = result.valid
      console.log(
        'validity',
        result.validity,
        result.valid,
        result.dirty,
        result.firstInvalidFieldIndex
      )
    },

    resetHandler (e) {
      console.log('reset', e)
    },

    areas (cbOk, cbErr) {
      this.$axios.get(apiShopAdmin.areas, null, cbOk, cbErr)
    },

    handleAreas () {
      let $this = this
      $this.areas(
        function (res) {
          let areaOptions = res.data.areas.map(item => {
            return {
              value: item.areaId,
              text: item.areaName
            }
          })
          $this.schema.groups[0].fields[2].props.options = areaOptions
        },
        function (err) {
          this.toast = this.$createToast({
            txt: err.msg,
            type: 'error'
          })
          this.toast.show()
        }
      )
    },

    shopCategories (cbOk, cbErr) {
      this.$axios.get(
        apiShopAdmin.shopCategories,
        {
          isParent: false
        },
        cbOk,
        cbErr
      )
    },

    handleShopCategories () {
      let $this = this
      $this.shopCategories(
        function (res) {
          let categoryOptions = res.data.shopCategories.map(item => {
            return {
              value: item.shopCategoryId,
              text: item.shopCategoryName
            }
          })
          $this.schema.groups[0].fields[1].props.options = categoryOptions
        },
        function (err) {
          $this.toast = $this.$createToast({
            txt: err.msg,
            type: 'error'
          })
          $this.toast.show()
        }
      )
    },

    handleRegisterShop (model) {
      let $this = this
      let param = new FormData()
      param.append('shopImg', model.shopImg[0].file)
      param.append('shopName', model.shopName)
      param.append('shopDesc', model.shopDesc)
      param.append('shopAddr', model.shopAddr)
      param.append('phone', model.shopPhone)
      param.append('areaId', model.shopArea)
      param.append('shopCategoryId', model.shopCategory)
      let config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      axios.post(apiShopAdmin.registerShop, param, config).then(response => {
        $this.toast = $this.$createToast({
          txt: '商铺注册成功',
          type: 'correct'
        })
        $this.toast.show()
      }).catch(error => {
        $this.toast = $this.$createToast({
          txt: error.msg,
          type: 'error'
        })
        $this.toast.show()
      })
    },

    checkVerifyCode (verifyCodeActual, cbOk, cbErr) {
      this.$axios.post(
        apiShopAdmin.checkVerifyCode,
        {
          verifyCodeActual
        },
        cbOk,
        cbErr
      )
    },

    handleCheckVerifyCode (verifyCodeActual) {
      let $this = this
      $this.checkVerifyCode(
        verifyCodeActual,
        function (res) {
          if (res.data.checked === true) {
            $this.handleRegisterShop($this.model)
          } else {
            $this.toast = $this.$createToast({
              txt: '验证码输入错误',
              type: 'error'
            })
            $this.toast.show()
          }
          $this.schema.groups[0].fields[8].props.sign *= -1
        }, function (err) {
          this.toast = this.$createToast({
            txt: err.msg,
            type: 'error'
          })
          this.toast.show()
        }
      )
    },

    handleSubmit () {
      this.handleCheckVerifyCode(this.model.verifyCode)
    }
  }
}
</script>

<style scoped>
</style>
